import { IInnerTreeNode, ITreeNode } from "./tree-types";

export function generateInnerTree(
	tree: ITreeNode[],
	level = 0,
	path = [] as IInnerTreeNode[]
): IInnerTreeNode[] {
	level++;
	return tree.reduce((pre, cur) => {
		const o = { ...cur } as IInnerTreeNode;
		o.level = level;
		// 记录调用栈，用于计算parentId 当到最后一层级时，清除记录栈，重新计算从第一级开始
		if (path.length > 0 && path[path.length - 1].level >= level) {
			// 子->父 向上冒泡 应该弹出栈顶
			while (path.length) {
				path.pop();
			}
		}
		// 记录 父->子
		path.push(o);
		// 获取parentNode
		const parentNode = path[path.length - 2];
		if (parentNode) {
			o.parentId = parentNode.id;
		}
		// 判断cur是否存在children，如果存在则递归遍历
		if (o.children) {
			// 首先递归，然后删除children
			const children = generateInnerTree(o.children, level, path);
			delete o.children;
			return pre.concat(o, children);
		} else {
			o.isLeaf = true;
			return pre.concat(o);
		}
	}, [] as IInnerTreeNode[]);
}
